<template>
  <div class="staff">
    <pagehead :rote="rote" />
    <!--  -->
    <div class="xzbox">
      <el-button type="primary" size="small" :icon="Plus" @click="open(null)"
        >新建</el-button
      >
      <el-button
        type="danger"
        size="small"
        :icon="Delete"
        @click="batchDelete"
        :disabled="multipleSelection.length === 0"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      :data="tableData.list"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="id" />
      <el-table-column prop="name" label="呢称" />
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="active" label="是否生效">
        <template #default="scope">
          <el-tag :type="scope.row.active == 1 ? 'success' : 'danger'">{{
            scope.row.sex == 1 ? "生效" : "失效"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="头像">
        <template #default="scope">
          <el-image style="width: 50px" :src="scope.row.avatar"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          <el-tag :type="scope.row.sex == 1 ? 'success' : 'danger'">{{
            scope.row.sex == 1 ? "男" : "女"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon><Clock /></el-icon>
            <span style="margin-left: 10px">{{
              formatDate(scope.row.create_time)
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" @click="open(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogTableVisible"
      title="陪护师添加与编辑"
      width="500"
      :before-close="handleClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item v-show="false" prop="id">
          <el-input v-model="form.id" />
        </el-form-item>
        <!-- 昵称 -->
        <el-form-item
          label="昵称"
          prop="name"
          label-width="100px"
          label-position="left"
        >
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请填写昵称"
          />
        </el-form-item>
        <!-- 头像 -->
        <el-form-item
          label="头像"
          prop="avatar"
          label-width="100px"
          label-position="left"
        >
          <el-button v-if="!form.avatar" type="primary" @click="ClickImage"
            >点击上传</el-button
          >
          <el-image
            v-else
            style="width: 100px"
            :src="form.avatar"
            class="imagewqq"
            @click="ClickImageChang"
          />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item
          label="性别"
          prop="sex"
          label-width="100px"
          label-position="left"
        >
          <el-select v-model="form.sex" placeholder="请选择你的性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <!-- 年龄 -->
        <el-form-item
          label="年龄"
          prop="age"
          label-width="100px"
          label-position="left"
        >
          <el-input-number v-model="form.age" :min="1" :max="90" />
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item
          label="手机号"
          prop="mobile"
          label-width="100px"
          label-position="left"
        >
          <el-input
            v-model="form.mobile"
            autocomplete="off"
            placeholder="请填写手机号"
          />
        </el-form-item>
        <!-- 是否生效 -->
        <el-form-item
          label="是否生效"
          prop="active"
          label-width="100px"
          label-position="left"
        >
          <el-radio-group v-model="form.active">
            <el-radio :value="0">失效</el-radio>
            <el-radio :value="1">生效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="consubmit(formRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="imageVisible"
      title="选择图片"
      width="680"
      :before-close="imageClose"
      align-center
    >
      <div class="image-grid">
        <div
          v-for="(imgUrl, index) in imageList"
          :key="index"
          class="image-item"
          @click="srcIndex = index"
        >
          <div v-if="srcIndex === index" class="gouxuan">
            <el-icon color="#fff"><Check /></el-icon>
          </div>
          <el-image :src="imgUrl" fit="cover" class="selectable-image">
          </el-image>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="imageVisible = false">取消</el-button>
          <el-button type="primary" @click="SelectPicture(srcIndex)"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// imports and composables
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  companionList,
  photoList,
  Companion,
  deleteCompanion,
} from "../../../api";
import { useRoute } from "vue-router";
import { Plus, Delete } from "@element-plus/icons-vue";
const rote = useRoute();
const dialogTableVisible = ref(false);
const imageVisible = ref(false);
const form = reactive({
  id: "",
  mobile: "",
  active: "",
  age: "",
  avatar: "",
  name: "",
  sex: "",
});
const formRef = ref();
const handleClose = () => {
  dialogTableVisible.value = false;
  // 重置表单
  formRef.value.resetFields();
};
const imageClose = () => {
  imageVisible.value = false;
};

const tableData = reactive({
  list: [],
  total: 0,
});
const paginationData = reactive({
  pageNum: 1, // 明确声明为数字
  pageSize: 10, // 明确声明为数字
});

const imageList = ref([]); // 存储图片列表
const src = ref(""); // 当前选中的图片地址
const srcIndex = ref(0);

const rules = reactive({
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  mobile: [{ required: true, message: "请输入你的手机号", trigger: "blur" }],
  sex: [{ required: true, message: "请选择你的性别", trigger: "blur" }],
  avatar: [{ required: true, message: "请上传图片", trigger: "blur" }],
});

const open = (rowData = {}) => {
  dialogTableVisible.value = true;
  nextTick(() => {
    if (rowData) {
      Object.assign(form, rowData);
      // treeRef.value.setCheckedKeys(rowData.permission);
    }
  });
};

const consubmit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const { id, mobile, active, age, avatar, name, sex } = form;
      Companion({ id, mobile, active, age, avatar, name, sex }).then(
        ({ data }) => {
          if (data.code === 10000) {
            ElMessage.success("成功");
            handleClose();
            getMenuList();
          }
        }
      );
    } else {
      console.log(fields, "fields");
      return false;
    }
  });
};

// 请求获取菜单权限列表数据
const getMenuList = () => {
  // console.log(paginationData);
  companionList(paginationData).then((data) => {
    // console.log(data);
    const { list, total } = data.data.data;
    tableData.list = list;
    tableData.total = total;
  });
};

const ClickImage = () => {
  imageVisible.value = true;
};

const SelectPicture = (index) => {
  form.avatar = imageList.value[index];
  imageVisible.value = false;
};
const ClickImageChang = (index) => {
  imageVisible.value = true;
};

function formatDate(date) {
  let data = new Date(date);
  const year = data.getFullYear();
  const month = String(data.getMonth() + 1).padStart(2, "0");
  const day = String(data.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

// 批量删除
const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的${multipleSelection.value.length}条记录吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      deleteCompanion({ id: multipleSelection.value }).then(({ data }) => {
        if (data.code === 10000) {
          ElMessage.success("批量删除成功");
          getMenuList(); // 刷新列表
        }
      });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

onMounted(() => {
  getMenuList();
  photoList().then(({ data }) => {
    // 将返回的图片数据存入 imageList
    imageList.value = data.data.map((item) => item.url);
  });
});
</script>

<style lang="less" scoped>
/* styles */
.xzbox {
  padding: 10px 0 10px 10px;
  background: #fff;
}
.paginationbox {
  padding: 10px 0;
  background: #fff;
  .el-pagination {
    padding-right: 50px;
    justify-content: flex-end;
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  padding: 10px;

  .image-item {
    cursor: pointer;
    transition: all 0.3s;
    width: 150px;
    height: 150px;
    .gouxuan {
      background: #5fe33a;
      position: absolute;
      z-index: 20;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .selectable-image {
    width: 150px;
    height: 150px;
    border-radius: 4px;
    border: 1px solid #eee;
  }
}
.imagewqq {
  cursor: pointer;
  transition: all 0.3s;
}
</style>